package com.joe.xl.devcommon1.util.kafka;

import com.joe.xl.devcommon1.util.kafka.interceptor.JoeProducerInterceptor;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.internals.DefaultPartitioner;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @Author joexl <joe_xuli@163.com>
 * @Since 1.0
 * @Date 2020/10/24
 */
public class KafkaProducerStart {
    private final static String KAFKA_SERVER_URL = "192.168.78.128:9092,192.168.78.128:9093,192.168.78.128:9094";

    public static void main(String... args){
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_SERVER_URL); // kafka服务器地址
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer .class.getName()); //key序列化器 可自定义
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); //值序列化器
        props.put(ProducerConfig.RETRIES_CONFIG, 3); //重试次数
        props.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, 1000); //重试次数间隔
        props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, DefaultPartitioner.class.getName()); //可以自定义分区器
        props.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, JoeProducerInterceptor.class.getName()); // 自定义拦截器
        props.put(ProducerConfig.ACKS_CONFIG, "1"); // 0默认 1 leader -1全部收到

        String topic = "testhello";
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(props);
        ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, "kafaka-demo", "hello, joe4");

        try {
            kafkaProducer.send(producerRecord);
        } catch (Exception e) {
            System.out.println("kafka error ...");
        }

        kafkaProducer.close();
    }

}
